﻿using RQX.Common.Core.Extension;
using RQX.Common.Core.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RQX.DataCollection.Main.Common
{
    public class FormUtils
    {
        /// <summary>
        /// 绑定下拉框combox的内容
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="list"></param>
        /// <param name="initValue"></param>
        /// <param name="initText"></param>
        public static void BindListItemToDDL(ComboBox comboBox, List<ListItem> list, int? initValue = null, string initText = null)
        {
            comboBox.DataSource = list;
            comboBox.ValueMember = "Value";
            comboBox.DisplayMember = "Text";

            float maxSize = 0;
            var g = comboBox.Parent.CreateGraphics();
            list.ForEach(item => maxSize = Math.Max(g.MeasureString(item.Text, comboBox.Font).Width, maxSize));
            comboBox.DropDownWidth = Math.Ceiling(maxSize).ToInt();

            if (initValue.HasValue)
            {
                var items = comboBox.Items.OfType<ListItem>().Where(k => k.Value.Equals(initValue.Value));
                if (items.Count() > 0)
                {
                    comboBox.SelectedIndex = comboBox.Items.IndexOf(items.FirstOrDefault());
                }
            }
            else if (initText.IsNotNullOrEmpty())
            {
                var items = comboBox.Items.OfType<ListItem>().Where(k => k.Text.Equals(initText));
                if (items.Count() > 0)
                {
                    comboBox.SelectedIndex = comboBox.Items.IndexOf(items.FirstOrDefault());
                }
            }
        }
        /// <summary>
        /// 找到下拉框的序号
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int FindDDLIndex(ComboBox comboBox,object value)
        {
            var items = comboBox.Items.OfType<ListItem>().Where(k => k.Value.Equals(value.ToString()) || k.Text.Equals(value.ToString()));
            if (items.Count() > 0)
            {
                return comboBox.Items.IndexOf(items.FirstOrDefault());
            }
            else
            {
                return -1;
            }
        }

        public static void ShowMsg(string msg)
        {
            MessageBox.Show(msg);
        }
    }
}
